﻿using RXY_Mall.Application.Marketing.Dto;
using RXY_Mall.Core;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace RXY_Mall.Application.Marketing
{
    public class MarketingService : IMarketingService
    {
        RXY_MallContext db = new RXY_MallContext();

        #region Banner
        public async Task<Response<GetBannerOutput>> GetBanner(int banner_id)
        {
            var result = new Response<GetBannerOutput>();
            result.msg = "保存失败";
            try
            {
                var banner = await db.gw_marketing_banners
                    .Where(b => b.id == banner_id)
                    .Select(item => new GetBannerOutput
                    {
                        add_time = item.add_time,
                        banner_id = item.id,
                        content = item.content,
                        picture_url = item.picture_url,
                        sort = item.sort,
                        status = item.status,
                        title = item.title,
                        type_id = item.type,
                    }
                    ).FirstOrDefaultAsync();

                result.code = 1;
                result.data = banner;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public Response<IPagedList<GetBannersOutput>> GetBanners(string start_date, string end_date, int status, int page_index = 1, int page_size = 20)
        {
            var result = new Response<IPagedList<GetBannersOutput>>();
            try
            {
                var source = db.gw_marketing_banners
                    //.Include(a => a.gw_base_advert_type)
                    .Select(item => new GetBannersOutput
                    {
                        add_time = item.add_time,
                        banner_id = item.id,
                        content = item.content,
                        picture_url = item.picture_url,
                        sort = item.sort,
                        status = item.status,
                        title = item.title,
                        type_id = item.type,
                        //type_name = item.gw_base_advert_type.name,
                    });

                if (status != -1)
                {
                    source = source.Where(s => s.status == status);
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    DateTime start;
                    if (DateTime.TryParse(start_date, out start))
                        source = source.Where(s => s.add_time > start);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    DateTime end;
                    if (DateTime.TryParse(end_date, out end))
                        source = source.Where(s => s.add_time <= end);
                }
                source = source.OrderByDescending(s => s.add_time);
                var pagelist = new PagedList<GetBannersOutput>(source, page_index, page_size);
                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetBannerOutput>> UpdateBanner(GetBannerOutput input)
        {
            var result = new Response<GetBannerOutput>();
            result.msg = "保存失败";
            try
            {
                if (input.type_id == 6)
                {
                    if (string.IsNullOrWhiteSpace(input.content))
                    {
                        result.msg = "内容不能为空";
                        return result;
                    }
                    int goods_id;
                    int.TryParse(input.content, out goods_id);
                    var goods = await db.gw_goods.FindAsync(goods_id);
                    if (goods == null)
                    {
                        result.msg = "没有该商品";
                        return result;
                    }
                    if (goods.type_id != (int)GoodsType.Ordinary)
                    {
                        result.msg = "只能添加普通商品";
                        return result;
                    }
                }


                var model = await db.gw_marketing_banners.FindAsync(input.banner_id);
                if (model == null)
                {
                    model = new Domain.gw_marketing_banner()
                    {
                        add_time = DateTime.Now,
                        content = input.content,
                        picture_url = input.picture_url,
                        sort = input.sort,
                        status = input.status,
                        title = input.title,
                        type = input.type_id,
                    };
                    db.gw_marketing_banners.Add(model);
                }
                else
                {
                    model.content = input.content;
                    model.picture_url = input.picture_url;
                    model.sort = input.sort;
                    model.status = input.status;
                    model.title = input.title;
                    model.type = input.type_id;
                    db.Entry(model).State = EntityState.Modified;
                }

                await db.SaveChangesAsync();
                result.code = 1;
                result.data = input;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<bool>> UpdateBannerStatus(UpdateBannerStatusInput input)
        {
            var result = new Response<bool>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_banners.FindAsync(input.banner_id);
                model.status = (byte)input.status;
                db.Entry(model).Property(m => m.status).IsModified = true;

                await db.SaveChangesAsync();

                result.code = 1;
                result.data = true;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }
        #endregion

        #region 首页商品

        public Response<IPagedList<GetHomeGoodsOutput>> GetHomeGoods(string start_date, string end_date, int status, int page_index = 1, int page_size = 20)
        {
            var result = new Response<IPagedList<GetHomeGoodsOutput>>();
            try
            {
                var source = db.gw_marketing_goods
                    .Include(g => g.gw_goods)
                    .Select(item => new GetHomeGoodsOutput
                    {
                        add_time = item.add_time,
                        picture_url = item.picture_url,
                        sort = item.sort,
                        status = item.status,
                        home_goods_id = item.id,
                        goods_name = item.gw_goods.name,
                        goods_id = item.goods_id,
                        type = item.type,
                    });

                if (status != -1)
                {
                    source = source.Where(s => s.status == status);
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    DateTime start;
                    if (DateTime.TryParse(start_date, out start))
                        source = source.Where(s => s.add_time > start);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    DateTime end;
                    if (DateTime.TryParse(end_date, out end))
                        source = source.Where(s => s.add_time <= end);
                }
                source = source.OrderByDescending(s => s.add_time);
                var pagelist = new PagedList<GetHomeGoodsOutput>(source, page_index, page_size);
                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<bool>> UpdateHomeGoodsStatus(UpdateHomeGoodsStatusInput input)
        {
            var result = new Response<bool>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_goods.FindAsync(input.home_goods_id);
                model.status = (byte)input.status;
                db.Entry(model).Property(m => m.status).IsModified = true;

                await db.SaveChangesAsync();

                result.code = 1;
                result.data = true;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetHomeGoodsOutput>> GetHomeGoods(int id)
        {
            var result = new Response<GetHomeGoodsOutput>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_goods
                    .Include(g => g.gw_goods)
                    .Where(b => b.id == id)
                    .Select(item => new GetHomeGoodsOutput
                    {
                        add_time = item.add_time,
                        picture_url = item.picture_url,
                        sort = item.sort,
                        status = item.status,
                        goods_id = item.goods_id,
                        home_goods_id = item.id,
                        type = item.type,
                        goods_name = item.gw_goods.name,
                    }
                    ).FirstOrDefaultAsync();

                result.code = 1;
                result.data = model;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetHomeGoodsOutput>> UpdateHomeGoods(GetHomeGoodsOutput input)
        {
            var result = new Response<GetHomeGoodsOutput>();
            result.msg = "保存失败";
            try
            {
                var goods = await db.gw_goods.FindAsync(input.goods_id);
                if (goods == null)
                {
                    result.msg = "没有该商品";
                    return result;
                }
                //if (goods.type_id != (int)GoodsType.Ordinary)
                //{
                //    result.msg = "只能添加普通商品";
                //    return result;
                //}

                var model = await db.gw_marketing_goods.FindAsync(input.home_goods_id);
                if (model == null)
                {
                    model = new Domain.gw_marketing_goods()
                    {
                        add_time = DateTime.Now,
                        picture_url = input.picture_url,
                        sort = input.sort,
                        status = input.status,
                        goods_id = input.goods_id,
                        type = 1,
                    };
                    db.gw_marketing_goods.Add(model);
                }
                else
                {
                    model.picture_url = input.picture_url;
                    model.sort = input.sort;
                    model.status = input.status;
                    model.goods_id = input.goods_id;
                    model.type = 1;
                    db.Entry(model).State = EntityState.Modified;
                }

                await db.SaveChangesAsync();
                result.code = 1;
                result.data = input;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<bool>> BatchAddHomeGood(BatchAddHomeGoodsInput input)
        {
            var result = new Response<bool>();
            result.msg = "保存失败";
            try
            {
                if (input == null || string.IsNullOrEmpty(input.goods_ids))
                {
                    result.msg = "没有该商品";
                    return result;
                }
                var lst = input.goods_ids.Split(',').ToList();
                List<int> lstIds = new List<int>();
                foreach (var item in lst)
                {
                    lstIds.Add(int.Parse(item));
                }
                var goods = await db.gw_goods.Where(g => lstIds.Contains(g.id)).ToListAsync();
                if (goods == null)
                {
                    result.msg = "没有该商品";
                    return result;
                }

                List<gw_marketing_goods> lstGoods = new List<gw_marketing_goods>();
                foreach (var item in goods)
                {
                    var model = new Domain.gw_marketing_goods()
                    {
                        add_time = DateTime.Now,
                        picture_url = item.gw_goods_picture.FirstOrDefault().url,
                        sort = 99,
                        status = 0,
                        goods_id = item.id,
                        type = 1,
                    };
                    lstGoods.Add(model);
                }

                db.gw_marketing_goods.AddRange(lstGoods);

                await db.SaveChangesAsync();
                result.code = 1;                
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }
        #endregion

        #region 优惠券
        public Response<IPagedList<GetCouponsOutput>> GetCoupons(string start_date, string end_date, int status, int page_index, int page_size)
        {
            var result = new Response<IPagedList<GetCouponsOutput>>();
            try
            {
                var source = db.gw_marketing_coupons
                    .Where(c => !c.deleted)
                   .Select(item => new GetCouponsOutput
                   {
                       add_time = item.add_time,
                       sort = item.sort,
                       status = item.status,
                       amount = item.amount,
                       coupon_id = item.id,
                       coupon_name = item.name,
                       coupon_type = item.type,
                       end_date = item.end_date,
                       remain_quantity = item.remain_quantity,
                       start_date = item.start_date,
                       total_quantity = item.total_quantity,
                       value = item.value,
                   });

                if (status != -1)
                {
                    source = source.Where(s => s.status == status);
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    DateTime start;
                    if (DateTime.TryParse(start_date, out start))
                        source = source.Where(s => s.add_time > start);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    DateTime end;
                    if (DateTime.TryParse(end_date, out end))
                        source = source.Where(s => s.add_time <= end);
                }
                source = source.OrderByDescending(s => s.add_time);
                var pagelist = new PagedList<GetCouponsOutput>(source, page_index, page_size);
                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<bool>> UpdateCouponStatus(UpdateCouponStatusInput input)
        {
            var result = new Response<bool>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_coupons.FindAsync(input.coupon_id);
                model.status = (byte)input.status;
                db.Entry(model).Property(m => m.status).IsModified = true;

                await db.SaveChangesAsync();

                result.code = 1;
                result.data = true;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetCouponOutput>> GetCoupon(int id)
        {
            var result = new Response<GetCouponOutput>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_coupons
                    .Include(g => g.gw_goods)
                    .Where(b => b.id == id)
                    .Select(item => new GetCouponOutput
                    {
                        add_time = item.add_time,
                        sort = item.sort,
                        status = item.status,
                        amount = item.amount,
                        coupon_id = item.id,
                        coupon_name = item.name,
                        coupon_type = item.type,
                        end_date = item.end_date,
                        remain_quantity = item.remain_quantity,
                        start_date = item.start_date,
                        total_quantity = item.total_quantity,
                        value = item.value,
                        is_all = item.is_all,
                        remark = item.remark,
                        description = item.description,
                        _goods_ids = item.gw_goods.Select(g => g.id).ToList(),
                    }
                    ).FirstOrDefaultAsync();
                if (model != null && model._goods_ids != null)
                {
                    model.goods_ids = string.Join(",", model._goods_ids);
                }

                result.code = 1;
                result.data = model;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetCouponOutput>> UpdateCoupon(GetCouponOutput input)
        {
            var result = new Response<GetCouponOutput>();
            result.msg = "保存失败";
            try
            {
                List<gw_goods> lstGoods = new List<gw_goods>();
                if (string.IsNullOrWhiteSpace(input.goods_ids))
                {
                    input.is_all = true;
                }
                else
                {
                    input.is_all = false;
                    var strgoods_ids = input.goods_ids.Split(',').ToList();
                    var goods_ids = new List<int>();
                    foreach (var item in strgoods_ids)
                    {
                        var id = 0;
                        if (int.TryParse(item, out id))
                            goods_ids.Add(id);
                    }

                    List<int> types = new List<int>();
                    types.Add((int)GoodsType.Memeber);
                    types.Add((int)GoodsType.Ordinary);

                    lstGoods = await db.gw_goods
                        .Where(g => types.Contains(g.type_id) && goods_ids.Contains(g.id)).ToListAsync();
                    if (lstGoods == null || lstGoods.Count == 0)
                    {
                        result.msg = "商品不存在";
                        return result;
                    }
                }

                if (input.end_date <= input.start_date)
                {
                    result.msg = "结束时间不能小于开始时间";
                    return result;
                }

                var model = await db.gw_marketing_coupons.Include(c => c.gw_goods).FirstOrDefaultAsync(c => c.id == input.coupon_id);
                if (model == null)
                {
                    model = new Domain.gw_marketing_coupon()
                    {
                        add_time = DateTime.Now,
                        sort = input.sort,
                        status = input.status,
                        amount = (decimal)input.amount,
                        end_date = (DateTime)input.end_date,
                        is_all = input.is_all,
                        deleted = false,
                        name = input.coupon_name,
                        remain_quantity = (int)input.total_quantity,
                        remark = input.remark,
                        start_date = (DateTime)input.start_date,
                        total_quantity = (int)input.total_quantity,
                        type = input.coupon_type,
                        value = (decimal)input.value,
                        description = input.description,
                    };
                    db.gw_marketing_coupons.Add(model);
                }
                else
                {
                    model.sort = input.sort;
                    model.status = input.status;
                    model.amount = (decimal)input.amount;
                    model.end_date = (DateTime)input.end_date;
                    model.is_all = input.is_all;
                    model.name = input.coupon_name;
                    model.remain_quantity = input.remain_quantity;
                    model.remark = input.remark;
                    model.start_date = (DateTime)input.start_date;
                    model.total_quantity = (int)input.total_quantity;
                    model.type = input.coupon_type;
                    model.value = (decimal)input.value;
                    model.description = input.description;

                    db.Entry(model).State = EntityState.Modified;
                }

                if (!input.is_all)
                {
                    foreach (var item in lstGoods)
                    {
                        if (!model.gw_goods.Contains(item))
                        {
                            model.gw_goods.Add(item);
                        }
                    }

                    foreach (var item in model.gw_goods)
                    {
                        if (!lstGoods.Contains(item))
                        {
                            model.gw_goods.Remove(item);
                        }
                    }
                }
                else
                {
                    model.gw_goods.Clear();
                }

                await db.SaveChangesAsync();
                result.code = 1;
                result.data = input;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        //批量修改
        public async Task<Response<bool>> BatchAddCoupon(BatchAddCouponInput input)
        {
            var result = new Response<bool>();
            result.msg = "保存失败";
            try
            {
                List<gw_goods> lstGoods = new List<gw_goods>();
                bool is_all = true;
                if (string.IsNullOrWhiteSpace(input.goods_ids))
                {
                    is_all = true;
                }
                else
                {
                    is_all = false;
                    var strgoods_ids = input.goods_ids.Split(',').ToList();
                    var goods_ids = new List<int>();
                    foreach (var item in strgoods_ids)
                    {
                        var id = 0;
                        if (int.TryParse(item, out id))
                            goods_ids.Add(id);
                    }

                    List<int> types = new List<int>();
                    types.Add((int)GoodsType.Memeber);
                    types.Add((int)GoodsType.Ordinary);

                    lstGoods = await db.gw_goods
                        .Where(g => types.Contains(g.type_id) && goods_ids.Contains(g.id)).ToListAsync();
                    if (lstGoods == null || lstGoods.Count == 0)
                    {
                        result.msg = "商品不存在";
                        return result;
                    }
                }

                if (input.end_date <= input.start_date)
                {
                    result.msg = "结束时间不能小于开始时间";
                    return result;
                }


                foreach (var item in input.coupon_values)
                {
                    if (item.value > item.amount)
                    {
                        result.msg = "优惠券价值不能大于优惠券使用金额";
                        return result;
                    }
                    var model = new Domain.gw_marketing_coupon()
                    {
                        add_time = DateTime.Now,
                        sort = 0,
                        status = 0,
                        amount = (decimal)item.amount,
                        end_date = (DateTime)input.end_date,
                        is_all = is_all,
                        deleted = false,
                        name = input.coupon_name,
                        remain_quantity = (int)item.total_quantity,
                        remark = input.remark,
                        start_date = (DateTime)input.start_date,
                        total_quantity = (int)item.total_quantity,
                        type = input.coupon_type,
                        value = (decimal)item.value,
                        description = input.description,
                    };
                    db.gw_marketing_coupons.Add(model);

                    if (!is_all)
                    {
                        foreach (var goods in lstGoods)
                        {
                            model.gw_goods.Add(goods);
                        }
                    }
                }

                await db.SaveChangesAsync();
                result.code = 1;
                result.data = true;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }
        #endregion

        #region 补贴商品
        public Response<IPagedList<GetSubsidiesOutput>> GetSubsidies(string start_date, string end_date, int status, int page_index, int page_size)
        {
            var result = new Response<IPagedList<GetSubsidiesOutput>>();
            try
            {
                var source = db.gw_marketing_returneds
                    .Where(c => !(bool)c.deleted)
                   .Select(item => new GetSubsidiesOutput
                   {
                       add_time = item.add_time,
                       status = item.status,
                       amount = item.amount,
                       subsidy_id = item.id,
                       subsidy_name = item.name,
                       end_time = item.end_time,
                       remain = item.remain,
                       start_time = item.start_time,
                   });

                if (status != -1)
                {
                    source = source.Where(s => s.status == status);
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    DateTime start;
                    if (DateTime.TryParse(start_date, out start))
                        source = source.Where(s => s.add_time > start);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    DateTime end;
                    if (DateTime.TryParse(end_date, out end))
                        source = source.Where(s => s.add_time <= end);
                }
                source = source.OrderByDescending(s => s.add_time);
                var pagelist = new PagedList<GetSubsidiesOutput>(source, page_index, page_size);
                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<bool>> UpdateSubsidyStatus(UpdateSubsidyStatusInput input)
        {
            var result = new Response<bool>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_returneds.FindAsync(input.subsidy_id);
                model.status = (byte)input.status;
                db.Entry(model).Property(m => m.status).IsModified = true;

                await db.SaveChangesAsync();

                result.code = 1;
                result.data = true;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<AddSubsidyInput>> GetSubsidy(int id)
        {
            var result = new Response<AddSubsidyInput>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_returneds
                    .Include(g => g.gw_goods)
                    .Where(b => b.id == id)
                    .Select(item => new AddSubsidyInput
                    {
                        amount = item.amount,
                        subsidy_id = item.id,
                        subsidy_name = item.name,
                        end_time = item.end_time,
                        start_time = item.start_time,
                        remark = item.remark,
                        _goods_ids = item.gw_goods.Select(g => g.id).ToList(),
                        subsidy_items = item.gw_marketing_returned_item.Select(i => new SubsidyItemInput
                        {
                            id = i.id,
                            quantity = i.quantity,
                            rate = i.returned_rate,
                            total_cycle = i.total_cycle,
                        }).ToList(),
                    }).FirstOrDefaultAsync();
                if (model != null && model._goods_ids != null)
                {
                    model.goods_ids = string.Join(",", model._goods_ids);
                }

                result.code = 1;
                result.data = model;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetSubsidyOutput>> UpdateSubsidy(GetSubsidyOutput input)
        {
            var result = new Response<GetSubsidyOutput>();
            result.msg = "保存失败";
            try
            {
                List<gw_goods> lstGoods = new List<gw_goods>();
                if (string.IsNullOrWhiteSpace(input.goods_ids))
                {
                    result.msg = "商品不能为空";
                    return result;
                }
                else
                {
                    var strgoods_ids = input.goods_ids.Split(',').ToList();
                    var goods_ids = new List<int>();
                    foreach (var item in strgoods_ids)
                    {
                        var id = 0;
                        if (int.TryParse(item, out id))
                            goods_ids.Add(id);
                    }

                    lstGoods = await db.gw_goods
                        .Where(g => g.type_id == (int)GoodsType.Ordinary && goods_ids.Contains(g.id)).ToListAsync();
                    if (lstGoods == null || lstGoods.Count == 0)
                    {
                        result.msg = "商品不存在";
                        return result;
                    }
                }

                if (input.end_time <= input.start_time)
                {
                    result.msg = "结束时间不能小于开始时间";
                    return result;
                }

                var model = await db.gw_marketing_returneds
                    .Include(c => c.gw_goods)
                    .Include(c => c.gw_marketing_returned_item)
                    .FirstOrDefaultAsync(c => c.id == input.subsidy_id);
                if (model == null)
                {
                    model = new Domain.gw_marketing_returned()
                    {
                        add_time = DateTime.Now,
                        status = input.status,
                        amount = (decimal)input.amount,
                        end_time = (DateTime)input.end_time,
                        deleted = false,
                        name = input.subsidy_name,
                        remain = (int)input.amount,
                        remark = input.remark,
                        start_time = (DateTime)input.start_time,
                    };
                    db.gw_marketing_returneds.Add(model);
                }
                else
                {
                    model.status = input.status;
                    model.amount = (decimal)input.amount;
                    model.end_time = (DateTime)input.end_time;
                    model.name = input.subsidy_name;
                    model.remark = input.remark;
                    model.start_time = (DateTime)input.start_time;
                    db.Entry(model).Property(m => m.status).IsModified = true;
                    db.Entry(model).Property(m => m.amount).IsModified = true;
                    db.Entry(model).Property(m => m.end_time).IsModified = true;
                    db.Entry(model).Property(m => m.name).IsModified = true;
                    db.Entry(model).Property(m => m.remark).IsModified = true;
                    db.Entry(model).Property(m => m.start_time).IsModified = true;

                    foreach (var item in input.subsidy_items)
                    {
                        var item_model = model.gw_marketing_returned_item.FirstOrDefault(i => i.id == item.id);
                        if (item_model == null)
                        {
                            item_model = new Domain.gw_marketing_returned_item()
                            {
                                add_time = DateTime.Now,
                                name = item.name,
                                remark = item.remark,
                                returned_id = model.id,
                                returned_rate = item.rate,
                                total_cycle = item.total_cycle,
                            };
                            model.gw_marketing_returned_item.Add(item_model);
                            //db.gw_marketing_returned_items.Add(item_model);
                        }
                        else
                        {
                            item_model.name = item.name;
                            item_model.remark = item.remark;
                            item_model.returned_rate = item.rate;
                            item_model.total_cycle = item.total_cycle;

                            db.Entry(item_model).State = EntityState.Modified;
                        }
                    }
                }

                foreach (var item in lstGoods)
                {
                    if (!model.gw_goods.Contains(item))
                    {
                        model.gw_goods.Add(item);
                    }
                }

                foreach (var item in model.gw_goods)
                {
                    if (!lstGoods.Contains(item))
                    {
                        model.gw_goods.Remove(item);
                    }
                }

                await db.SaveChangesAsync();
                result.code = 1;
                result.data = input;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetSubsidyItemOutput>> GetSubsidyItem(int id)
        {
            var result = new Response<GetSubsidyItemOutput>();
            try
            {
                var source = await db.gw_marketing_returned_items
                   .Select(item => new GetSubsidyItemOutput
                   {
                       add_time = item.add_time,
                       subsidy_id = item.returned_id,
                       name = item.name,
                       rate = item.returned_rate,
                       remark = item.remark,
                       total_cycle = item.total_cycle,
                       id = item.id,
                   }).FirstOrDefaultAsync(i => i.id == id);

                result.code = 1;
                result.data = source;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetSubsidyItemOutput>> UpdateSubsidyItem(GetSubsidyItemOutput input)
        {
            var result = new Response<GetSubsidyItemOutput>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_returned_items.FirstOrDefaultAsync(c => c.id == input.id);
                if (model == null)
                {
                    model = new Domain.gw_marketing_returned_item()
                    {
                        add_time = DateTime.Now,
                        name = input.name,
                        remark = input.remark,
                        returned_id = input.subsidy_id,
                        returned_rate = input.rate,
                        total_cycle = input.total_cycle,
                    };
                    db.gw_marketing_returned_items.Add(model);
                }
                else
                {

                    model.name = input.name;
                    model.remark = input.remark;
                    model.returned_rate = input.rate;
                    model.total_cycle = input.total_cycle;

                    db.Entry(model).State = EntityState.Modified;
                }

                await db.SaveChangesAsync();
                result.code = 1;
                result.data = input;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<bool>> AddSubsidy(AddSubsidyInput input)
        {
            var result = new Response<bool>();
            result.msg = "保存失败";
            try
            {
                List<gw_goods> lstGoods = new List<gw_goods>();
                if (string.IsNullOrWhiteSpace(input.goods_ids))
                {
                    result.msg = "商品不能为空";
                    return result;
                }
                else
                {
                    var strgoods_ids = input.goods_ids.Split(',').ToList();
                    var goods_ids = new List<int>();
                    foreach (var item in strgoods_ids)
                    {
                        var id = 0;
                        if (int.TryParse(item, out id))
                            goods_ids.Add(id);
                    }

                    lstGoods = await db.gw_goods
                        .Where(g => g.type_id == (int)GoodsType.Ordinary && goods_ids.Contains(g.id)).ToListAsync();
                    if (lstGoods == null || lstGoods.Count == 0)
                    {
                        result.msg = "商品不存在";
                        return result;
                    }
                }

                if (input.end_time <= input.start_time)
                {
                    result.msg = "结束时间不能小于开始时间";
                    return result;
                }

                var model = new gw_marketing_returned()
                {
                    add_time = DateTime.Now,
                    status = 0,
                    amount = (decimal)input.amount,
                    end_time = (DateTime)input.end_time,
                    deleted = false,
                    name = input.subsidy_name,
                    remain = (int)input.amount,
                    remark = input.remark,
                    start_time = (DateTime)input.start_time,
                };
                db.gw_marketing_returneds.Add(model);

                foreach (var item in input.subsidy_items)
                {
                    var item_model = new Domain.gw_marketing_returned_item()
                    {
                        add_time = DateTime.Now,
                        quantity = item.quantity,
                        returned_id = model.id,
                        returned_rate = item.rate,
                        total_cycle = item.total_cycle,
                    };
                    model.gw_marketing_returned_item.Add(item_model);
                }

                foreach (var item in lstGoods)
                {
                    if (!model.gw_goods.Contains(item))
                    {
                        model.gw_goods.Add(item);
                    }
                }

                await db.SaveChangesAsync();
                result.code = 1;
                result.data = true;
                result.msg = "保存成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetSubsidyOutput>> GetSubsidy2(int id)
        {
            var result = new Response<GetSubsidyOutput>();
            result.msg = "保存失败";
            try
            {
                var model = await db.gw_marketing_returneds
                    .Include(g => g.gw_goods)
                    .Where(b => b.id == id)
                    .Select(item => new GetSubsidyOutput
                    {
                        //add_time = item.add_time,
                        status = item.status,
                        amount = item.amount,
                        subsidy_id = item.id,
                        subsidy_name = item.name,
                        end_time = item.end_time,
                        remain = item.remain,
                        start_time = item.start_time,
                        remark = item.remark,
                        _goods_ids = item.gw_goods.Select(g => g.id).ToList(),
                        subsidy_items = item.gw_marketing_returned_item.Select(i => new GetSubsidyItemOutput
                        {
                            add_time = i.add_time,
                            id = i.id,
                            name = i.name,
                            remark = i.remark,
                            rate = i.returned_rate,
                            subsidy_id = i.returned_id,
                            total_cycle = i.total_cycle,
                        }).ToList(),
                    }).FirstOrDefaultAsync();
                if (model != null && model._goods_ids != null)
                {
                    model.goods_ids = string.Join(",", model._goods_ids);
                }

                result.code = 1;
                result.data = model;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        #endregion
    }
}
